﻿using Microsoft.AspNetCore.Authorization;

namespace ChatGpt_WebApp.Fillter;

public class IpAddressRequirement : IAuthorizationRequirement
{
    public string[] AllowedIpAddresses { get; }

    public IpAddressRequirement(IEnumerable<string> allowedIpAddresses)
    {
        AllowedIpAddresses = allowedIpAddresses.ToArray();
    }
}

public class IpAddressAuthorizationHandler : AuthorizationHandler<IpAddressRequirement>
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public IpAddressAuthorizationHandler(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IpAddressRequirement requirement)
    {
        var remoteIpAddress = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "";
        if (remoteIpAddress != null && requirement.AllowedIpAddresses.Contains(remoteIpAddress.ToString()))
        {
            context.Succeed(requirement);  // IP 地址符合要求，授权成功
        }

        return Task.CompletedTask;
    }
}


